package com.xiaodu.mybatis.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Properties;

/**
 * @author: dutianjie
 * @date: 2021/4/20
 * @version: v1.0.0
 * @description: 描述
 **/
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class DateInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object arg = args[1];
        Executor executor = (Executor) invocation.getTarget();
        Field createTime = ReflectionUtils.findField(arg.getClass(), "createTime");
        Field updateTime = ReflectionUtils.findField(arg.getClass(), "updateTime");
        if (createTime != null && sqlCommandType.equals(SqlCommandType.INSERT)) {
            fieldSet(arg, createTime);
        }

        if (updateTime != null && sqlCommandType.equals(SqlCommandType.UPDATE)) {
            fieldSet(arg, updateTime);
        }
        return executor.update(mappedStatement, arg);
    }

    private void fieldSet(Object arg, Field f) {
        ReflectionUtils.makeAccessible(f);
        Class<?> type = f.getType();
        if (type == Date.class) {
            ReflectionUtils.setField(f, arg, new Date());
        } else if (type == java.sql.Date.class) {
            ReflectionUtils.setField(f, arg, new java.sql.Timestamp(new Date().getTime()));

        } else if (type == LocalDateTime.class) {
            ReflectionUtils.setField(f, arg, LocalDateTime.now());
        } else if (type == LocalDate.class) {
            ReflectionUtils.setField(f, arg, LocalDate.now());
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
